﻿using AutoMapper;
using MediatR;
using PublicClass;
using S.Breeding.Domain;
using S.Breeding.Infrastructure;
using S.Breeding.Read.Api.Application.Command.OustManageCommand;

namespace S.Breeding.Read.Api.Application.CommandHandlers.OustManageCommandHandlers
{
    public class OustManageListCommandHandlers : IRequestHandler<OustManageListCommand, PageInfo<OustManage>>
    {
        private readonly IRepository<OustManage> repository;
        private readonly PageInfo<OustManage> pageInfo;
        private readonly IMapper mapper;
        public OustManageListCommandHandlers(IRepository<OustManage> repository, IMapper mapper, PageInfo<OustManage> pageInfo)
        {
            this.repository = repository;
            this.mapper = mapper;
            this.pageInfo = pageInfo;
        }

        public async Task<PageInfo<OustManage>> Handle(OustManageListCommand request, CancellationToken cancellationToken)
        {
            var list = repository.All().Result;
            if (!string.IsNullOrEmpty(request.Earbugles))
            {
                list = list.Where(x => x.Earbugles == request.Earbugles);
            }
            if (request.Sdate != null)
            {
                list = list.Where(x => x.OustTime >= request.Sdate);
            }
            if (request.Edate != null)
            {
                list = list.Where(x => x.OustTime <= request.Edate);
            }
            if (request.OustCause > 0)
            {
                list = list.Where(x => x.OustCause == request.OustCause);
            }
            if (request.Lingchatan > 0)
            {
                list = list.Where(x => x.Lingchatan == request.Lingchatan);
            }
            pageInfo.totalCount = list.Count();
            pageInfo.pageCount = (int)Math.Ceiling(pageInfo.totalCount * 1.0 / request.pageSize);
            list = list.OrderByDescending(x => x.OustTime).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize);
            return new PageInfo<OustManage>
            {
                datas = list.ToList(),
                totalCount = pageInfo.totalCount,
                pageCount = pageInfo.pageCount,
            };
        }
    }
}
